package com.kc.sjwh.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;

import com.kc.sjwh.entity.bo.UserBo;
import com.kc.sjwh.other.MyToken;

/**
 * action基类
 * @author zhangguihua(hua7381@163.com)
 * date: 2017年7月20日
 */
public class BaseAction {
	
	/**
	 * 获取当前登陆用户
	 * @param req
	 * @return
	 */
	protected UserBo getLoginUser() {
		return (UserBo) ((MyToken)SecurityUtils.getSubject().getPrincipal()).getUser();
	}
	
	/**
	 * 获取所有请求参数map
	 * @param req
	 * @return
	 */
	protected Map<String,String> getParamMap(HttpServletRequest req) {
		Map<String, String[]> reqParams = req.getParameterMap();
		Map<String, String> params = new HashMap<String, String>();
		for(String key : reqParams.keySet()) {
			String[] arr = reqParams.get(key);
			if(arr.length > 1) {
				String v = "";
				for(int i=0; i<arr.length; i++) {
					if(v.length() > 0) {
						v += ",";
					}
					v += arr[i];
				}
				params.put(key, v);
			} else {
				params.put(key, arr[0]);
			}
		}
		return params;
	}
	
	/**
	 * 判断请求是否为ajax
	 * @param req
	 * @return
	 */
	protected boolean isAjax(HttpServletRequest req) {
		return req.getHeader("accept").contains("application/json") || 
				(req.getHeader("X-Requested-With") != null && req.getHeader("X-Requested-With").contains("XMLHttpRequest"));
	}
	
	/**
	 * 通过response返回(写)字符串
	 * @param resp
	 * @param str
	 */
	protected void write(HttpServletResponse resp, String str) {
		PrintWriter writer = null;
		try {
			resp.setCharacterEncoding("UTF-8");
			writer = resp.getWriter();
			writer.write(str);
			writer.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if(writer != null) {
				writer.close();
			}
		}
	}
}
